<?php
/**
 * System Utils class Do not include into packages!
 * @author Kirill A Egorov
 */
class Utils{
 	/**
     * Create an array from another array using field as key
     * @param string $key
     * @param array $data
     * @throws Exception
     * @return array
     */
    static public function rekey($key , array $data){
        $result = array();
        
        foreach ( $data as $k=>$v){          
            if(!isset($v[$key]))
                throw new Exception('Invalid key');
                
             $result[$v[$key]] = $v;     
        }
        
        return  $result;
    }
    /**
     * Collect data from resultset
     * @param string $keyField
     * @param string $valueField
     * @param array $data
     * @return array
     */
    static public function collectData($keyField , $valueField, $data){
    	$result = array();
    	foreach($data as $k=>$v){
    		if(!array_key_exists($keyField , $v) || !array_key_exists($valueField , $v))
    			throw new Exception('Invalid key');
    		$result[$v[$keyField]]	 = $v[$valueField];   			
    	}
    	return $result;
    }
     /**
      * Fetch array column
      * @param string $key
      * @param array $data
      * @throws Exception
      * @return array
      */
    static public function fetchCol($key , array $data){
        $result = array();
        
        if(empty($data))
            return array();
            
        foreach ($data as $v){                  
            if(!isset($v[$key]))
                trigger_error('Invalid key');             
             $result[] = $v[$key];  
        }      
        return  $result;    
    }
    /**
     * Group array by column, used for db results sorting
     * @param string $key
     * @param array $data
     * @return array
     */
    static public function groupByKey($key , array $data){
    	$result = array();
        
        if(empty($data))
            return array();
            
         foreach ($data as $v){                  
            if(!isset($v[$key]))
                trigger_error('Invalid key');             
             $result[$v[$key]][] = $v;  
         }        
         return $result;   
    }
    /**
     * Get hash for the string
     * @param string $string
     * @throws Exception
     * @return string
     */
    static public function hash($string){
        $store = Store_Local::getInstance();
        if(!$store->keyExists('config_main'))
            throw new Exception('At first it is necessary to instantiate the application');
        
        $sault = Store_Local::getInstance()->get('config_main')->get('sault');
        return md5(md5($string . $sault . $string));   
    }
    /**
     * Prints object or an array in html format
     * @param mixed $object
     */
    static public function debug($object){
        echo '<pre>';
        print_r($object);
        echo '</pre>';
    }

    static protected function _scanClassDir($path , &$map , $exceptPath , $packMap){
        $path = File::fillEndSep($path);
        $items = File::scanFiles($path , array('.php'), false);
 
        if(empty($items))
            return;
            
        foreach ($items as $item){
                if(File::getExt($item) === '.php')
                {
                    $parts = explode(DIRECTORY_SEPARATOR, str_replace($exceptPath,'', substr($item,0,-4)));
       				$parts = array_map('ucfirst', $parts);
       				$package = '';
       				
       				if(array_key_exists($item, $packMap))
       					$package = $packMap[$item];
       					
       				$map[implode('_', $parts)] =  array('file'=>$item,'package'=>$package);
                }
                else
                {
                   self::_scanClassDir($item, $map, $exceptPath , $packMap);   
                }
        }
    }
    
    
    static protected function _createPackagesMap(Config_File_Array $config)
    {
    	$packages = $config->get('packages');    	
    	$packMap = array();
    	if(!empty($packages))
    		foreach ($packages as $key=>$items)
    			if(!empty($items))
    				foreach ($items['paths'] as $index=>$path)
    					$packMap[$path] = $key;
    					   					
    	return  $packMap;				
    }
    /**
     * Scan files and create class map for autoloader
     * @param array $startPaths - paths for scan (relative paths)
     * @param string $destFile - output phpfile path
     * @param Config_File_Array - $packagesConfig
     * @return void
     */
    static public function createClassMap(array $startPaths ,  $destFile , Config_File_Array $packagesConfig)
    {
    	$packMap = self::_createPackagesMap($packagesConfig);

        $map = array();
        foreach ($startPaths as $k=>$v)
            self::_scanClassDir($v, $map, $v , $packMap);
        
        ksort($map);
   		file_put_contents($destFile, '<?php return ' . var_export($map , true).'; ');
    }
    /**
     * Format file size in user friendly
     * @param integer $size
     * @return string
     */
    static public function formatFileSize($size){
    	/*
    	 * 1024 * 1024 * 1024  - Gb
    	 */
    	if($size > 1073741824)
    		return number_format($size / 1073741824 , 1 ).' Gb';  	
    	/*
    	 * 1024 * 1024 - Mb
    	 */
    	if($size > 1048576)
    		return number_format($size / 1048576 , 1 ).' Mb'; 
    	/*
    	 * 1024  - Kb
    	 */
    	if($size > 1024)
    		return number_format($size / 1024 , 1 ).' Kb';	
    		
    	return 	$size.' B';	
    }
    /**
     * Format time
     * @param integer $difference
     * @return string
     */
    static public function formatTime($difference)
    {
    	/*if($time < 60)
    		return $time .' sec.';

    	return self::findTime($time );
    	*/
    		$days = floor($difference / 86400);
            $difference = $difference % 86400;
            $hours = floor($difference / 3600);
            $difference = $difference % 3600;
            $minutes = floor($difference / 60);
            $difference = $difference % 60;
            $seconds =  floor($difference);
            if($minutes == 60){
                $hours = $hours+1;
                $minutes = 0;
            }
            $s='';
            
            if($days >0)
            	$s.= $days.' days ';
            
            $s.= str_pad($hours,2,'0',STR_PAD_LEFT).':'.str_pad($minutes,2,'0',STR_PAD_LEFT).':'.str_pad($seconds,2,'0',STR_PAD_LEFT);         	
            return $s; 
    }
    /**
     * Export php array into the file
     * @param string $file
     * @param array $data
     * @return boolean;
     */
    static public function exportArray($file , array $data){
    	return file_put_contents($file, '<?php return ' . var_export($data , true).'; ');
    }
    /**
     * Export php code
     * @param string $file
     * @param string $string
     * @return boolean
     */
    static public function exportCode($file , $string){
    	return file_put_contents($file, '<?php ' . $string);
    }
}